﻿using Sasa.QualityTools.CodeAnalysis.Common;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels;
using System;
using System.Collections.Generic;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Searching
{
    internal class SearcherGeneratorFacade
    {
        private static Dictionary<string, ISearcherGenerator> mapping;


        internal Func<ProblemViewModel, bool> Generate(string word)
        {
            var tokens = SplitWord(word);
            var generator = GetInstance(tokens.Item1);

            Logger.Info("Created the searcher generator: type={0}, word={1}", generator.GetType().FullName, tokens.Item2);

            return generator.Generate(tokens.Item2);
        }

        private Tuple<string, string> SplitWord(string word)
        {
            if (word == null)
            {
                return Tuple.Create("", "");
            }
            else if (word.Contains(":"))
            {
                string[] values = word.Split(new char[] { ':' }, 2, StringSplitOptions.None);
                return Tuple.Create(values[0], values[1]);
            }
            else
            {
                return Tuple.Create("", word);
            }
        }

        private ISearcherGenerator GetInstance(string keyword)
        {
            if (mapping == null)
            {
                mapping = new Dictionary<string, ISearcherGenerator>();
                mapping.Add("category", new CategorySearcherGenerator());
                mapping.Add("c", new CategorySearcherGenerator());
                mapping.Add("id", new CheckIdSearcherGenerator());
                mapping.Add("file", new FileNameSearcherGenerator());
                mapping.Add("f", new FileNameSearcherGenerator());
                mapping.Add("kind", new KindSearcherGenerator());
                mapping.Add("k", new KindSearcherGenerator());
                mapping.Add("message", new MesseageSearcherGenerator());
                mapping.Add("m", new MesseageSearcherGenerator());
                mapping.Add("project", new ProjectNameSearcherGenerator());
                mapping.Add("p", new ProjectNameSearcherGenerator());
            }
            return (!String.IsNullOrWhiteSpace(keyword) && mapping.ContainsKey(keyword)) ? mapping[keyword] : new DefaultSearcherGenerator();
        }
    }
}
